package org.springblade.modules.develop.beetl.function;

import java.util.HashMap;
import java.util.Map;

import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springblade.modules.develop.beetl.utils.TplUtils;

public class RenderFunction implements Function{
	private Logger logger=LoggerFactory.getLogger(RenderFunction.class);
	private GroupTemplate gt;
	
	@Override
	public String call(Object[] paras, Context ctx) {
		this.gt=ctx.gt;
		String result="";
		try{
			JSONArray jSONArray = JSONArray.parseArray((String)paras[0]);
			String key=(String)paras[1];
			JSONObject jSONObject= TplUtils.findJsonObjectByKey(jSONArray, key);
			result=render(jSONObject);
		}catch(Exception e){
			logger.error("渲染错误:",e);
		}
		return result;
	}

	public String render(JSONObject json){
		String result="";
		JSONArray children=json.getJSONArray("children");
		if(children!=null){
			for(int i=0;i<children.size();i++){
				return render(children.getJSONObject(i));
			}
		}
		String type=json.getString("type");
		String templatePath=TplUtils.getTplPathByType(type);
		Template t = gt.getTemplate(templatePath);
		Map<String, Object> paras = new HashMap<>();
		paras.put("json", json);
		t.fastBinding(paras);
		result=t.render();
		return result;
	}
}
